package com.wuage.infrastructure.handler;

import com.wuage.infrastructure.exception.BizException;
import com.wuage.infrastructure.status.BizResultCode;
import com.wuage.infrastructure.utils.Response;
import com.wuage.infrastructure.utils.ResponseBuild;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局的的异常拦截器
 * @author shynin
 */
@Slf4j
@RestControllerAdvice
@ControllerAdvice
public class  GlobalExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Response exceptionHandler(Exception e) {
        log.error("this is global exception handler, error message is {}", e.getMessage(), e);
        return ResponseBuild.fail(BizResultCode.SYSTEM_ERROR);
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public Response exceptionHandler(MethodArgumentNotValidException e) {
        return ResponseBuild.fail(e.getBindingResult().getFieldError().getDefaultMessage());
    }

    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public Response exceptionHandler(BizException e) {
        return ResponseBuild.fail(e.getErrorCode(), e.getErrorMsg());
    }

}
